#例【3-1】
import json
import uuid
from datetime import datetime

request_object = {
    "model": "deepseek-chat",
    "root_id": str(uuid.uuid4()),
    "resources": [
        {"role": "system", "content": "你是一个招聘助理"},
        {"role": "user", "content": "请根据简历生成岗位匹配度分析"}
    ],
    "config": {
        "temperature": 0.7,
        "max_tokens": 512,
        "stream": False
    },
    "metadata": {
        "request_id": str(uuid.uuid4()),
        "caller": "resume-analysis-agent",
        "timestamp": datetime.utcnow().isoformat()
    }
}

# 打印结构化请求
print(json.dumps(request_object, ensure_ascii=False, indent=2))



#例【3-2】
import uuid
import json

def simulate_mcp_response(success=True):
    if success:
        return {
            "status": "success",
            "trace_id": str(uuid.uuid4()),
            "outputs": [
                {
                    "role": "assistant",
                    "content": "岗位匹配度为85%，建议进入初试阶段"
                }
            ],
            "context_updates": [
                {
                    "type": "append_prompt",
                    "role": "assistant",
                    "content": "岗位匹配分析结果已生成"
                }
            ]
        }
    else:
        return {
            "status": "error",
            "trace_id": str(uuid.uuid4()),
            "error": {
                "code": "TOOL_CALL_FAILED",
                "message": "工具调用失败，参数缺失",
                "detail": "调用 resume_parser 缺少 resume_text 字段"
            },
            "outputs": []
        }

# 打印响应结果（成功 + 失败两种）
print("=== 成功响应示例 ===")
print(json.dumps(simulate_mcp_response(True), indent=2, ensure_ascii=False))

print("\n=== 异常响应示例 ===")
print(json.dumps(simulate_mcp_response(False), indent=2, ensure_ascii=False))



#例【3-3】
import uuid
import json
from datetime import datetime

# 构造带有元数据的Request对象
request_object = {
    "model": "deepseek-chat",
    "root_id": str(uuid.uuid4()),
    "resources": [
        {
            "role": "system",
            "content": "你是一个招聘助手",
            "metadata": {
                "context_origin": "system_default",
                "weight": 1.0
            }
        },
        {
            "role": "user",
            "content": "请帮我分析这个候选人的技能是否匹配",
            "metadata": {
                "topic": "resume_analysis",
                "trigger_plugin": True,
                "external_resume_id": "resume_12345"
            }
        }
    ],
    "config": {
        "temperature": 0.5,
        "stream": False
    },
    "metadata": {
        "request_id": str(uuid.uuid4()),
        "caller": "agent.hr.bot",
        "timestamp": datetime.utcnow().isoformat(),
        "env": "production",
        "task_type": "semantic_tool_chain"
    }
}

# 输出结构化请求对象
print(json.dumps(request_object, indent=2, ensure_ascii=False))



#例【3-4】
import json
import uuid
from datetime import datetime

# 构造一个合法的MCP请求体
request_object = {
    "model": "deepseek-chat",
    "root_id": str(uuid.uuid4()),
    "resources": [
        {
            "role": "system",
            "content": "你是一个会议纪要助手",
            "metadata": {
                "context_origin": "preset_system",
                "weight": 1.0
            }
        },
        {
            "role": "user",
            "content": "请根据这段对话生成会议摘要",
            "metadata": {
                "external_doc_id": "meeting_20240401",
                "trigger_plugin": True
            }
        }
    ],
    "config": {
        "temperature": 0.7,
        "max_tokens": 512,
        "stream": False
    },
    "metadata": {
        "request_id": str(uuid.uuid4()),
        "caller": "meeting-agent-v1",
        "timestamp": datetime.utcnow().isoformat(),
        "task_type": "doc_summarization"
    }
}

# 校验与输出JSON格式
try:
    serialized = json.dumps(request_object, ensure_ascii=False, indent=2)
    print("✅ JSON结构合法，格式如下：\n")
    print(serialized)
except Exception as e:
    print("❌ JSON格式错误：", e)



#例【3-5】
class MCPError(Exception):
    def __init__(self, code, message, detail=None):
        self.code = code
        self.message = message
        self.detail = detail or "无详细信息"
    def to_dict(self):
        return {
            "status": "error",
            "error": {
                "code": self.code,
                "message": self.message,
                "detail": self.detail
            }
        }
# 模拟一个执行场景
def simulate_tool_call(params):
    if not params.get("resume_text"):
        raise MCPError(
            code="TOOL_FAIL_002",
            message="工具调用失败：缺少必要参数",
            detail="resume_text 字段未提供，无法生成分析"
        )
    return {"status": "success", "result": "匹配度为 90%"}
# 示例调用与错误捕获
try:
    result = simulate_tool_call({"user_id": "u01"})
except MCPError as e:
    result = e.to_dict()

# 输出结果
import json
print(json.dumps(result, indent=2, ensure_ascii=False))



#例【3-6】
import json

# 模拟服务端生成的部分响应
def generate_response_part(content, complete=False):
    return {
        "status": "success",
        "outputs": [
            {
                "role": "assistant",
                "content": content,
                "metadata": {
                    "continue_flag": not complete
                }
            }
        ]
    }

# 客户端执行处理逻辑
response1 = generate_response_part("这是第一段输出，", complete=False)
response2 = generate_response_part("这是最终段落，生成完毕。", complete=True)

# 输出两段响应结构
print("=== 第一段响应 ===")
print(json.dumps(response1, indent=2, ensure_ascii=False))

print("\n=== 第二段响应 ===")
print(json.dumps(response2, indent=2, ensure_ascii=False))



#例【3-7】
# 模拟缓存对象池
context_cache = {}

# 缓存写入函数
def store_context(session_id, prompt_block):
    context_cache[session_id] = {
        "content": prompt_block,
        "version": "v1.0",
        "timestamp": "2025-04-10T12:00:00Z"
    }
# 缓存读取函数
def load_context(session_id):
    return context_cache.get(session_id, None)
# 写入一段上下文缓存
session_id = "session_user_123"
prompt_structure = [
    {"role": "system", "content": "你是一个项目管理助手"},
    {"role": "user", "content": "请帮我整理今天的会议重点"}
]
store_context(session_id, prompt_structure)
# 读取缓存并注入当前请求
cached = load_context(session_id)
if cached:
    print("成功命中缓存，已加载上下文：")
    for p in cached["content"]:
        print(f"- {p['role']}：{p['content']}")
else:
    print("无可用上下文缓存")



#例【3-8】
import time
# 模拟系统中的Token结构
VALID_TOKEN = {
    "token": "abc123securetoken456",
    "user_id": "user_001",
    "scope": "chat_access",
    "expires_at": time.time() + 3600  # 1小时后过期
}
def verify_token(token_input):
    if token_input != VALID_TOKEN["token"]:
        return {"status": "error", "error": "无效Token，认证失败"}
    if time.time() > VALID_TOKEN["expires_at"]:
        return {"status": "error", "error": "Token已过期"}
    return {"status": "success", "user_id": VALID_TOKEN["user_id"]}

# 模拟一次请求验证
print("=== 使用合法Token进行验证 ===")
print(verify_token("abc123securetoken456"))

print("\n=== 使用错误Token进行验证 ===")
print(verify_token("invalid_token_789"))